<template>
    <div class="main">
        <!--顶部操作栏-->
        <div class="tool_bar">
            <!--添加产品按钮-->
            <el-button @click="add_flag=true" class="el-button2" icon="el-icon-plus" size="small" circle></el-button>
        </div>
        <!--表格-->
        <el-table
        :data="products" align="center" height="500">
            <!--自增indext值-->
            <el-table-column header-align="center" align="center" type="index" width="50"></el-table-column>
            <!--产品标题-->
            <el-table-column header-align="center" align="center" label="标题" width="180">
                <span class="title" slot-scope="scope">{{scope.row.title}}</span>
            </el-table-column>
            <!--产品内容：若超出则裁剪-->
            <el-table-column header-align="center" label="内容" width="300">
                <div class="content" slot-scope="scope">{{scope.row.content}}</div>
            </el-table-column>
            <!--产品图片-->
            <el-table-column header-align="center" align="center" label="图片" width="180">
                <img class="pic" slot-scope="scope" :src="scope.row.picture"/>
            </el-table-column>
            <!--产品状态-->
            <el-table-column header-align="center" align="center" label="状态" width="70">
                <!--使按钮根据0和1进行展示，0表示未启用，1表示启用-->
                <el-switch @change="showChange(scope.row)" slot-scope="scope" v-model="scope.row.state_using" :inactive-value="0" :active-value="1" active-color="#13ce66" inactive-color="#C0C4CC"></el-switch>   
            </el-table-column>
            <!--操作-->
            <el-table-column header-align="center" align="center" label="操作" width="180">
                <template slot-scope="scope">
                    <!--编辑：显示表单，并将当前产品的所有信息写入到data中-->
                    <el-button @click="showEditDialog(scope.row),dialog_flag=true" type="primary" icon="el-icon-edit" size="mini">编辑</el-button>
                    <!--删除：弹出对话框-->
                    <el-button @click="handleDelete(scope.row.id)" type="danger" icon="el-icon-delete" size="mini">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!--分页-->
        <el-pagination 
            background layout="prev, pager, next" 
            :total="pageInfo.total" :page-size="pageInfo.sumItem"
            @prev-click="handlePrevClick" @next-click="handleNextClick" @current-change="handleCurrentChange">
        </el-pagination>
        <!--隐藏的编辑对话框-->
        <el-dialog class="el_dialog" width="60%" :visible.sync="dialog_flag" :closeOnClickModal="false" :showClose="false">
            <!--表单-->
            <el-form ref="form_update" :rules="form_update_rules" 
                class="visible_form" :model="current_product">
                <!--标题-->
                <el-form-item prop="title" label="标题" label-width="60px">
                    <el-input class="title" v-model="current_product.title" maxlength="50" show-word-limit></el-input>
                </el-form-item>
                <!--图片-->
                <el-form-item class="mypc" label="图片" label-width="60px">
                    <div class="picture">
                        <!--左侧原图-->
                        <div>
                            <img class="pic" :src="current_product.picture"/>
                            <div class="pre_tip">原始图片</div>
                        </div>
                        <!--右侧新图-->
                        <div>
                            <!--如果返回图片url则显示，否则显示加载页面-->
                            <div style="margin-left:20px">
                                <img v-if="pre_picture!=''" class="pic" :src="pre_picture"/>
                                <div v-else class="pic center border">
                                    <i class="fa fa-spinner fa-pulse" style="font-size:60px;"></i>
                                </div>
                            </div>
                            <!--设置允许携带Cookie-->
                            <el-upload
                                name="file"
                                :action="update_url"
                                :before-upload="beforeUpload"
                                :on-success="handleUpLoad"
                                :with-credentials="true"
                                :limit="1"
                                :file-list="file"
                                >
                                <el-button class="update_button" size="small" type="primary">更新图片</el-button>
                            </el-upload>
                        </div>  
                    </div>
                </el-form-item>
                <!--内容-->
                <el-form-item prop="content" label="内容" label-width="60px">
                    <el-input class="content" :rows="6" type="textarea" v-model="current_product.content" maxlength="250" show-word-limit></el-input>
                </el-form-item>
                <!--信息：创建者以及创建时间一定存在，而更新者不一定存在，故要进行判断，看是否存在更新者-->
                <el-form-item label="信息" class="message_form" label-width="60px">
                    <el-row>
                        <el-col :span="12">创建者：{{current_product.founder.name}}<span>(</span>{{current_product.founder.username}}<span>)</span></el-col>
                        <el-col :span="12">创建时间：{{current_product.create_time}}</el-col>
                    </el-row>
                    <!--如果更新者不存在，则显示空串，避免报空异常-->
                    <el-row v-if="current_product.updater">
                        <el-col :span="12">更新者：{{current_product.updater.name}}<span>(</span>{{current_product.updater.username}}<span>)</span></el-col>
                        <el-col :span="12">修改时间：{{current_product.update_time}}</el-col>
                    </el-row>
                    <el-row v-else>
                        <el-col :span="12">更新者：无</el-col>
                        <el-col :span="12">修改时间：无</el-col>
                    </el-row>
                </el-form-item>            
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="clearAll">取消</el-button>
                <el-button @click="Save" type="primary">更新</el-button>
            </div>        
        </el-dialog>
        <!--隐藏的添加对话框：添加增添功能-->
        <el-dialog class="el_dialog" width="60%" :visible.sync="add_flag" :closeOnClickModal="false" :showClose="false">
            <el-form ref="form_add" :rules="form_add_rules" :model="add_product">
                <el-form-item prop="title" label="标题" label-width="60px">
                    <el-input v-model="add_product.title" maxlength="50" show-word-limit></el-input>
                </el-form-item>
                <el-form-item label="图片" label-width="60px">
                    <div>
                        <!--如果返回图片url则显示，否则显示加载页面-->
                        <img v-if="pre_picture!=''" class="pic" :src="pre_picture"/>
                        <div v-else class="pic center border">
                            <i class="fa fa-spinner fa-pulse" style="font-size:60px;"></i>
                        </div>
                    </div>
                    <el-upload
                        name="file"
                        :action="update_url"
                        :before-upload="beforeUpload"
                        :on-success="handleUpLoad"
                        :with-credentials="true"
                        :limit="1"
                        :file-list="file">
                        <el-button class="update_button" size="small" type="primary">上传图片</el-button>
                    </el-upload>
                </el-form-item>
                <el-form-item prop="content" label="内容" label-width="60px">
                    <el-input v-model="add_product.content" :rows="6" type="textarea" maxlength="250" show-word-limit></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="clearAll">取消</el-button>
                <el-button @click="Add" type="primary">添加</el-button>
            </div> 
        </el-dialog>
    </div>
</template>

<script>
export default {
    created(){
        this.getAllProducts()      //获取所有产品信息
        this.selectItemsNumber()   //获取产品个数
    },
    data(){
        return{
            update_url:"http://localhost:9000/product/upload", //图片上传的url地址
            pre_picture:"",                        //预览图片
            file:[],                               //图片列表
            products:[],                           //接收当前页的产品信息
            pageInfo:{page:1,sumItem:3,total:0},   //当前页数、每页个数(预设)、总个数(在数据库中查询)
            current_product:{
                id:"",title:"",picture:"",content:"",
                create_time:"",update_time:"",
                founder:{id:0,name:"",username:""},
                updater:{id:0,name:"",username:""}
            },                                     //当前正在编辑的产品
            add_product:{
                title:"",
                content:""
            },                                     //当前正在添加的产品
            dialog_flag:false,                     //是否显示编辑对话框
            add_flag:false,                        //是否显示添加对话框
            form_update_rules:{
                title:[
                    {required:true,message:"此项为必填项",trigger:"blur"}
                ],
                content:[
                    {required:true,message:"此项为必填项",trigger:"blur"}
                ]
            },
            form_add_rules:{
                title:[
                    {required:true,message:"此项为必填项",trigger:"blur"}
                ],
                content:[
                    {required:true,message:"此项为必填项",trigger:"blur"}
                ]
            }
        }
    },
    methods:{
        //获取所有产品信息
        async getAllProducts(){
            const{data:res}=await this.$http.post("/product/select",this.pageInfo)
            //如果传值不为空
            if(res.flag==0){
                this.products=res.data
            }
        },
        //获取产品总个数(修改data中的数据)
        async selectItemsNumber(){
            const{data:res}=await this.$http.post("/product/selectItemsNumber")
            this.pageInfo.total=res
        },
        //逻辑删除单个产品
        handleDelete(id){
            this.$confirm('将永久删除该图片且不可恢复, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
                closeOnClickModal:false,    //关闭点击屏幕外侧触发关闭
                showClose:false             //关闭右上角叉叉
            }).then(async () => {
                //点击了确定
                const{data:res}=await this.$http.post("/product/delete","id="+id)
                if(res.flag==0){
                    //若当前页不为第一页，且删除此记录后页面置空，则将页号-1(避免出现删除记录后出现空页面的效果)
                    if(this.pageInfo.page!=1&&(this.products.length-1)==0){
                        this.pageInfo.page=this.pageInfo.page-1
                    }
                    //解决当前记录为第一页的第一条，删除后仍存在的bug
                    if(this.pageInfo.page==1&&(this.products.length-1)==0){
                        this.products=[]
                    }
                    //刷新product页面
                    this.getAllProducts()
                    //查询总个数
                    this.selectItemsNumber()
                    this.$message.success("删除成功！")
                }else{
                    this.$message.error("删除失败！")
                }
            }).catch(() => {
                //点击了取消
                this.$message("已取消")
            })
        },
        //用户点击switch按钮，对产品是否在前端进行展示进行修改
        async showChange(product){
            var id=product.id
            var state=product.state_using
            const{data:res}=await this.$http.post("/product/updateStateUsingById?id="+id+"&state="+state)
            //修改成功后，不再提示，而仅有失败时给予提示
            if(res.flag!=0){
                this.$message.error("状态更改失败！")
            }
        },
        //将用户点击的产品的信息放入到data中
        showEditDialog(product){
            this.current_product=product
        },
        //用户点击了上一页
        handlePrevClick(current_page){
            this.pageInfo.page=current_page
            this.getAllProducts() //刷新页面
        },
        //用户点击了下一页
        handleNextClick(current_page){
            this.pageInfo.page=current_page
            this.getAllProducts() //刷新页面
        },
        //用户选择某页
        handleCurrentChange(current_page){
            this.pageInfo.page=current_page
            this.getAllProducts() //刷新页面
        },
        //检验
        beforeUpload(file){
            //判断图片格式是否正确
            if(file.type=="image/jpeg"||file.type=="image/png"){
            //判断图片大小(单位:字节)是否正确
            if(file.size<=1024*1024){
                return true            
            }else{
                this.$message.error("图片尺寸应小于等于2M")
                return false
            }
            }else{
                this.$message.error("图片只能上传为.jpg格式或.png格式的图片")
                return false
            }
        },
        //用户点击了取消
        clearAll(){
            //清空上传图片信息
            this.file=[]
            this.pre_picture=""
            //关闭编辑对话框
            this.dialog_flag=false
            //关闭添加对话框
            this.add_flag=false
        },
        //上传图片(后台将上传图片到阿里云，并设置Session存储url地址)
        handleUpLoad(response){
            if(response.flag==0){
                this.$message.success("上传成功！")
                //将图片展示为修改的url
                this.pre_picture=response.url
            }else{
                this.$message.error("上传失败！")
            }
        },
        //用户点击了保存
        Save(){
            //1.前端验证
            this.$refs.form_update.validate(async valid=>{
                //前端验证通过
                if(valid){
                    const{data:res}=await this.$http.post("/product/update",this.current_product)
                    if(res.flag==0){
                        this.getAllProducts() //刷新页面
                        this.$message.success("修改成功！")
                    }else{
                        this.$message.error("修改失败！")
                    }
                    //清空各种信息并关闭对话框
                    this.clearAll()
                }
            })
        },
        //用户点击了添加
        Add(){
            //前端验证
            this.$refs.form_add.validate(async valid=>{
                if(valid){
                    const {data:res}=await this.$http.post("/product/addProduct",this.add_product)
                    if(res.flag==0){
                        this.getAllProducts() //刷新页面
                        //查询总个数
                        this.selectItemsNumber()
                        this.$message.success("添加成功！")
                    }else{
                        this.$message.error("添加失败！")
                    }
                    //清空各种信息并关闭对话框
                    this.clearAll()
                }
            })
        }
    }
}
</script>

<style lang="less" scoped>
    .main{
        margin:20px auto;
        width:80%;
    }
    .tool_bar{
        height:50px;
        background-color:#409EFF;
        display:flex;
        align-items:center;
        .el-button1{
            position:absolute;
            right:14%;
        }
        .el-button2{
            position:absolute;
            right:11%;
        }
    }
    .el-table{
        /**标题 */
        .title{
            font-weight:600;
        }
        /*内容*/
        .content{
            //隐藏多余四行的文字，避免显示时太过冗余
            font-weight:500;
            width:100%;
            overflow: hidden;
            display: -webkit-box;
            -webkit-line-clamp:4;
            -webkit-box-orient: vertical;
        }
        /**图片 */
        .pic{
            width:100px;
            height:100px;
        }
    }
    .el-pagination{
        margin-top:10px;
        text-align: center;
    }
    /*隐藏的编辑样式*/
    .pic{
        /*图片格式*/
        width:200px;
        height:200px;
    }
    .el_dialog{
        margin-top:-100px;
        //表单
        .visible_form{
            user-select:none;
            .el-form-item{
                margin:0 auto;
                width:90%;
            }
            .message_form{
                margin-top:20px;
            }
        }
        .mypc{
            box-sizing:border-box;
            padding-top:20px;
            padding-bottom:10px;
            .picture{
                display:flex;
                //更新产品时"上传图片"按钮
                .update_button{
                    margin-left:80px;
                    margin-top:12px;
                }
            }
        }
        //添加产品时"上传图片"按钮
        .update_button{
            margin-left:60px;
        }
        .pre_tip{
            border-radius:5px;
            background-color:rgb(94, 243, 218);
            margin-left:50px;
            width:90px;
            line-height:32px;
            padding-left:19px;
            box-sizing:border-box;
            font-size:13px;
            color:white;
            font-weight:500;
            text-shadow:1px 1px 1px #ccc;
        }
    }
    .center{
        display:flex;
        justify-content:center;
        align-items:center;
    }
    .border{
        border:solid 1px #EBEEF5;
    }
</style>